package com.xoa.service.cms;

import com.xoa.dao.cms.CmsChannelInfoMapper;
import com.xoa.dao.cms.CmsChnldocMapper;
import com.xoa.dao.cms.CmsDocumentInfoMapper;
import com.xoa.dao.cms.CmsSiteInfoMapper;
import com.xoa.model.cms.*;
import com.xoa.model.users.Users;
import com.xoa.service.cms.core.FileUtils;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author 程叶同
* @date 2018/8/13 14:36
* @desc  cms文档管理
*/
@Service
public class CmsDocumentService {

    @Autowired
    CmsDocumentInfoMapper documentInfoMapper;
    @Autowired
    EnclosureService enclosureService;
    @Autowired
    CmsChnldocMapper cmsChnldocMapper;
    @Autowired
    CmsChannelInfoMapper channelInfoMapper;
    @Autowired
    CmsSiteInfoMapper siteInfoMapper;


    /**
     * 添加文档
     * @param documentInfoModel
     * @return
     */
    public CmsChnldoc addDocument(HttpServletRequest request, DocumentInfoModel documentInfoModel){
        //TeeRequestInfo requestInfo = TeeRequestInfoContext.getRequestInfo();
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        //保存文档实体
        CmsDocumentInfoWithBLOBs info = new CmsDocumentInfoWithBLOBs();
        BeanUtils.copyProperties(documentInfoModel, info);
        info.setWriteTime(FileUtils.parseCalendar(documentInfoModel.getWriteTimeDesc()));
        info.setCrTime(new Date());
        info.setStatus(0);//发布状态
        info.setCrUserid(user.getUid());
        info.setCrUsername(user.getUserName());

        int thumbnail = 0;//缩略图
        String content=info.getHtmlContent();
        List oldUrls = new ArrayList();
        List newUrls = new ArrayList();
        oldUrls = FileUtils.getImageSrc(content);
        if(oldUrls!=null && oldUrls.size()>0){
            for(int i=0;i<oldUrls.size();i++){
                String urls=(String) oldUrls.get(i);
                newUrls.add(urls);
            }
        }
        String newContent = FileUtils.replaceImageUrl(oldUrls, content, newUrls);
        info.setHtmlContent(newContent);
        //提取第一张图片作为缩略图
        if(thumbnail==0){
            String urls="/download/?AID";
            Pattern p = Pattern.compile("<img[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(newContent);
            String quote = null;
            String src = null;
            while (m.find()) {
                quote = m.group(1);  //判断是否有双引号和单引号
                src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
                thumbnail = FileUtils.getInteger(src.replace(urls, ""), 0);
                break;
            }
        }
        info.setThumbnail(thumbnail);
        documentInfoMapper.insertSelective(info);

        //保存chnlDoc关系
        CmsChnldoc chnlDoc = new CmsChnldoc();
        chnlDoc.setChnlId(documentInfoModel.getChnlId());
        chnlDoc.setCrTime(new Date());
        chnlDoc.setDocId(info.getSid());
        chnlDoc.setTop(documentInfoModel.getTop());
        chnlDoc.setType(1);
        //获取最大sortNo
        Long max = getDocMaxSortNo(info.getChnlId());
        if (max == null) {
            max=(long)0;
        }
        chnlDoc.setSortNo(Integer.parseInt(String.valueOf(max+1)));

        cmsChnldocMapper.insertSelective(chnlDoc);

        //业务处理
        //chnlDoc.getSid();
        CmsChannelInfo channelInfo=channelInfoMapper.selectByPrimaryKey(chnlDoc.getChnlId());
        String[] channelInfos=channelInfo.getPath().split("/");
        String str1="/";
        for (String str : channelInfos) {
            int i=str.indexOf(".");
            if(i==-1){continue;}
            str=str.substring(0, i);//数字sid
            int id= Integer.parseInt(str);
            channelInfo = channelInfoMapper.selectByPrimaryKey(id);

            str1=str1+channelInfo.getFolder()+"/";

        }
        CmsSiteInfo siteInfoModel = siteInfoMapper.selectByPrimaryKey(channelInfo.getSiteId());
        chnlDoc.setPath(str1+chnlDoc.getSid()+"."+siteInfoModel.getPubFileExt());
        chnlDoc.setDocId(info.getSid());
        cmsChnldocMapper.updateByPrimaryKeySelective(chnlDoc);
        return chnlDoc;
    }

    /**
     * 获取指定栏目下文档的最大排序号
     * @param channelId
     * @return
     */
    public Long getDocMaxSortNo(int channelId){
        return cmsChnldocMapper.getMaxSortNo(channelId);
    }

    /**
     * 更新文档
     * @param documentInfoModel
     */
    public void updateDocument(DocumentInfoModel documentInfoModel, HttpServletRequest request){
        //获取之前的数据
        String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        CmsDocumentInfoWithBLOBs documentInfo = getDocumentByDocId(documentInfoModel.getDocId());
        documentInfo.setStatus(4);//已发
        documentInfo.setDocTitle(documentInfoModel.getDocTitle());
        documentInfo.setAbstracts(documentInfoModel.getAbstracts());
        documentInfo.setHtmlContent(documentInfoModel.getHtmlContent());
        documentInfo.setContent(documentInfoModel.getContent());
        documentInfo.setMainTitle(documentInfoModel.getMainTitle());
        documentInfo.setSubTitle(documentInfoModel.getSubTitle());
        documentInfo.setKeyWords(documentInfoModel.getKeyWords());
        documentInfo.setSource(documentInfoModel.getSource());
        documentInfo.setAuthor(documentInfoModel.getAuthor());
        documentInfo.setCategory(documentInfoModel.getCategory());
        documentInfo.setWriteTime(FileUtils.parseCalendar(documentInfoModel.getWriteTimeDesc()));

        //获取对应chnlDoc
        CmsChnldoc chnlDoc = getChnlDocByDocAndChnl(documentInfoModel.getDocId(),documentInfoModel.getChnlId());
        chnlDoc.setTop(documentInfoModel.getTop());
        CmsChannelInfo channelInfo=channelInfoMapper.selectByPrimaryKey(chnlDoc.getChnlId());
        String[] channelInfos=channelInfo.getPath().split("/");
        String str1="/";
        for (String str : channelInfos) {
            int i=str.indexOf(".");
            if(i==-1){continue;}
            str=str.substring(0, i);//数字sid
            int id= Integer.parseInt(str);
            channelInfo = channelInfoMapper.selectByPrimaryKey(id);
            str1=str1+channelInfo.getFolder()+"/";
        }

        CmsSiteInfo siteInfoModel = siteInfoMapper.selectByPrimaryKey(channelInfo.getSiteId());

        chnlDoc.setPath(str1+chnlDoc.getSid()+"."+siteInfoModel.getPubFileExt());



        int thumbnail = documentInfoModel.getThumbnail();//缩略图
        String content=documentInfo.getHtmlContent();
        List oldUrls = new ArrayList();
        List newUrls = new ArrayList();
        oldUrls = FileUtils.getImageSrc(content);
        if(oldUrls!=null && oldUrls.size()>0){
            for(int i=0;i<oldUrls.size();i++){
                String urls=(String)oldUrls.get(i);
                newUrls.add(urls);

            }
        }
        String newContent = FileUtils.replaceImageUrl(oldUrls, content, newUrls);

        //提取第一张图片作为缩略图
        if(thumbnail==0){
            String urls="/download/?AID=";
            Pattern p = Pattern.compile("<img[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(newContent);
            String quote = null;
            String src = null;
            while (m.find()) {
                quote = m.group(1);  //判断是否有双引号和单引号
                src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("\\s+")[0] : m.group(2);
                thumbnail = FileUtils.getInteger(src.replace(urls, ""), 0);
                break;
            }
        }
        documentInfo.setThumbnail(thumbnail);

        documentInfo.setHtmlContent(newContent);

        documentInfoMapper.updateByPrimaryKeyWithBLOBs(documentInfo);

    }
    public CmsChnldoc getChnlDocByDocAndChnl(int docId, int chnlId){
        return cmsChnldocMapper.getChnlDocByDocAndChnl(docId,chnlId);
    }

    public BaseWrapper deleteDocumentByChnlDoc(List<Integer> docids){
        BaseWrapper baseWrapper=new BaseWrapper();
        CmsChnldocExample cmsChnldocExample=new CmsChnldocExample();
        CmsChnldocExample.Criteria criteria = cmsChnldocExample.createCriteria();
        criteria.andSidIn(docids);
        List<CmsChnldoc> chnlDocs = cmsChnldocMapper.selectByExample(cmsChnldocExample);
//        CmsChnldoc chnlDoc=null;
        if (chnlDocs.size() > 0) {
            for (CmsChnldoc chnlDoc : chnlDocs) {
                if (chnlDoc != null) {
                    if(chnlDoc.getType()==1){//如果是原链接，则予以删除document实体
                        cmsChnldocMapper.deleteByExample(cmsChnldocExample);
                        CmsDocumentInfoExample cmsDocumentInfoExample=new CmsDocumentInfoExample();
                        CmsDocumentInfoExample.Criteria criteria1 = cmsDocumentInfoExample.createCriteria();
                        criteria1.andSidEqualTo(chnlDoc.getChnlId());
                        int i=documentInfoMapper.deleteByExample(cmsDocumentInfoExample);
                        if (i > 0) {
                            baseWrapper.setFlag(true);
                            baseWrapper.setStatus(true);
                        }
                    }else{//仅仅删除
                        int i=cmsChnldocMapper.deleteByExample(cmsChnldocExample);
                        if (i > 0) {
                            baseWrapper.setFlag(true);
                            baseWrapper.setStatus(true);
                        }
                    }
                }
            }
        }

        return baseWrapper;
    }

    public CmsChnldoc getChnlDoc(int chnlId, int docId){
        CmsChnldocExample cmsChnldocExample=new CmsChnldocExample();
        CmsChnldocExample.Criteria criteria = cmsChnldocExample.createCriteria();
        criteria.andChnlIdEqualTo(chnlId);
        criteria.andDocIdEqualTo(docId);
        List<CmsChnldoc> cmsChnldocs = cmsChnldocMapper.selectByExample(cmsChnldocExample);
        CmsChnldoc chnlDoc=null;
        if (cmsChnldocs.size() > 0) {
            chnlDoc = cmsChnldocs.get(0);
        }
        return chnlDoc;
    }

    public CmsChnldoc getChnlDoc(int chnlDocId){
        CmsChnldoc chnlDoc = cmsChnldocMapper.selectByPrimaryKey(chnlDocId);
        return chnlDoc;
    }

    public List<Map> getPublishableDocumentsByChnlId(int channelId, int from, int to, String orderBy, String category) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
        List<Map> data=new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        map.put("channelId",channelId);
        map.put("orderBy",orderBy);
        map.put("from",from);
        map.put("to",to);
        data=documentInfoMapper.getPublishableDocumentsByChnlId(map);
       // List<Map> data = simpleDaoSupport.getMaps(hql, null,from,to);
        return data;
    }


    /**
     * 通过chnlDocId获取文档
     * @param chnlDocId
     * @return
     */
    public Map getDocumentByChnlDocId(int chnlDocId) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
        Map data = documentInfoMapper.getDocumentByChnlDocId(chnlDocId);
        return data;
    }


    public CmsDocumentInfoWithBLOBs getDocumentByDocId(int docId){
        CmsDocumentInfoWithBLOBs documentInfo = documentInfoMapper.selectByPrimaryKey(docId);
        return documentInfo;
    }


    /**
     * 获取可发布的文档的数量
     * @param channelId
     * @return
     */
    public long getPublishableDocumentsCountByChnlId(int channelId){
        long count = documentInfoMapper.getPublishableDocumentsCountByChnlId(channelId);

        return count;
    }



    /**
     * 通过栏目lds获取文档信息
     * @param
     * @return
     */
    public List<Map> getDocumentByChnlIds(String ids, int top, String orderBy, String category){
        Map<String,Object> map=new HashMap<>();
        map.put("ids",ids);
        map.put("top",top);
        List<Map> documentByChnlIds = documentInfoMapper.getDocumentByChnlIds(map);


        return documentByChnlIds;
    }

    public BaseWrapper datagrid(Integer channelId, boolean useFlag, Integer pageSize, Integer page){
        BaseWrapper baseWrapper = new BaseWrapper();

        Map<String,Object> map=new HashMap<>();
        PageParams pageParams=new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPageSize(pageSize);
        pageParams.setPage(page);
        map.put("channelId",channelId);
        map.put("pageParams",pageParams);
        List<CmsDocumentInfoWithBLOBs> list=new ArrayList<>();
        list = documentInfoMapper.datagrid(map);
        baseWrapper.setTotleNum(pageParams.getTotal());
        baseWrapper.setData(list);


        return baseWrapper;
    }

    public void moveToTrash(List<Integer> docids){
        CmsChnldocExample cmsChnldocExample=new CmsChnldocExample();
        CmsChnldocExample.Criteria criteria = cmsChnldocExample.createCriteria();
        criteria.andDocIdIn(docids);
        CmsChnldoc chnldoc=new CmsChnldoc();
        chnldoc.setDelFlag(1);
        cmsChnldocMapper.updateByExampleSelective(chnldoc,cmsChnldocExample);
    }

    public BaseWrapper clearTrash(int channelId){
        BaseWrapper baseWrapper=new BaseWrapper();
        CmsChnldocExample cmsChnldocExample=new CmsChnldocExample();
        CmsChnldocExample.Criteria criteria = cmsChnldocExample.createCriteria();
       criteria.andChnlIdEqualTo(channelId);
       criteria.andDelFlagEqualTo(1);
       criteria.andTypeNotEqualTo(1);
        //先删除该栏目下所有非原始chnlDoc
        cmsChnldocMapper.deleteByExample(cmsChnldocExample);
        //再取出原始chnlDoc
        List<CmsChnldoc> chnlDocs = cmsChnldocMapper.selectByExample(cmsChnldocExample);

        for(CmsChnldoc cd:chnlDocs){
            CmsDocumentInfoExample documentInfoExample=new CmsDocumentInfoExample();
            CmsDocumentInfoExample.Criteria criteria1 = documentInfoExample.createCriteria();
            criteria1.andSidEqualTo(cd.getDocId());
            documentInfoMapper.deleteByExample(documentInfoExample);
        }
        CmsChnldocExample cmsChnldocExample1=new CmsChnldocExample();
        CmsChnldocExample.Criteria criterias = cmsChnldocExample1.createCriteria();
        criterias.andChnlIdEqualTo(channelId);
        criterias.andDelFlagEqualTo(1);
        criterias.andTypeEqualTo(1);
        int i=cmsChnldocMapper.deleteByExample(cmsChnldocExample1);
        if (i > 0) {
            baseWrapper.setFlag(true);
            baseWrapper.setMsg("ok");
            baseWrapper.setStatus(true);
        }
        return  baseWrapper;
    }

    public int recycle(List<Integer> docids){
        CmsChnldocExample cmsChnldocExample1=new CmsChnldocExample();
        CmsChnldocExample.Criteria criterias = cmsChnldocExample1.createCriteria();
        criterias.andSidIn(docids);
        CmsChnldoc cmsChnldoc=new CmsChnldoc();
        cmsChnldoc.setDelFlag(0);
         int i =cmsChnldocMapper.updateByExampleSelective(cmsChnldoc,cmsChnldocExample1);
         return i;
    }
    public BaseWrapper datagridTrash(Integer channelId, boolean useFlag, Integer pageSize, Integer page){
        BaseWrapper baseWrapper=new BaseWrapper();

        Map<String,Object> map=new HashMap<>();
        PageParams pageParams=new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPageSize(pageSize);
        pageParams.setPage(page);
        map.put("channelId",channelId);
        map.put("pageParams",pageParams);
        List<CmsDocumentInfoWithBLOBs> list=new ArrayList<>();
        list = cmsChnldocMapper.datagridTrash(map);
        baseWrapper.setTotleNum(pageParams.getTotal());
        baseWrapper.setData(list);


        return baseWrapper;
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/5/24
     * @说明: 更新文档状态 0未发布 1已发布
     */
    public BaseWrapper updateCmsDocumentStatus(CmsDocumentInfoWithBLOBs documentInfoModel){
        BaseWrapper baseWrapper=new BaseWrapper();
        documentInfoMapper.updateByPrimaryKeySelective(documentInfoModel);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/5/27
     * @说明: 根据栏目id查询该栏目下的已发布的文章 带分页
     */
    public BaseWrapper selCmsDocs(Integer chnlId, PageParams pageParams){
        BaseWrapper baseWrapper=new BaseWrapper();
        Map<String,Object> map = new HashMap<String,Object>();

        map.put("page",pageParams);
        map.put("chnlId",chnlId);

        List<CmsDocumentInfoWithBLOBs> cmsDocumentInfoWithBLOBs = documentInfoMapper.selCmsDocs(map);

        baseWrapper.setData(cmsDocumentInfoWithBLOBs);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        baseWrapper.setTotleNum(pageParams.getTotal());

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/3
     * @说明: 获取首页轮播（暂时查询五个）
     */
    public BaseWrapper selCarousel(){
        BaseWrapper baseWrapper=new BaseWrapper();

        List<CmsDocumentInfoWithBLOBs> cmsDocumentInfoWithBLOBs = documentInfoMapper.selCarousel();

        for (int i=0,size=cmsDocumentInfoWithBLOBs.size();i<size;i++){
            CmsDocumentInfoWithBLOBs cmsDocumentInfoWithBLOBs1 = cmsDocumentInfoWithBLOBs.get(i);
            if(!StringUtils.checkNull(cmsDocumentInfoWithBLOBs1.getHtmlContent())){
                Set<String> imgSrc = getImgSrc(cmsDocumentInfoWithBLOBs1.getHtmlContent());
                cmsDocumentInfoWithBLOBs1.setImgSrc(imgSrc.iterator().next());
                cmsDocumentInfoWithBLOBs1.setHtmlContent(null);
            }
        }
        baseWrapper.setData(cmsDocumentInfoWithBLOBs);
        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/6/3
     * @说明: 获取html元素中的图片地址
     */
    public static Set<String> getImgSrc(String htmlStr) {
        Set<String> pics = new HashSet<>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                //System.out.println(m.group(1));
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
